# 验证类
from urllib.parse import unquote

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import APIException
from django.core.exceptions import ObjectDoesNotExist

from luckin.common import get_token, base64_decode
from luckin.models import User


class TokenAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.COOKIES.get("token", "")
        cookie_arg1 = request.COOKIES.get("cookie_arg1", "")
        cookie_arg1 = unquote(cookie_arg1)
        if token != get_token(cookie_arg1):
            raise APIException("token 错误")
        account = base64_decode(cookie_arg1)
        try:
            user = User.objects.get(phone=account)
            return user, user.id
        except ObjectDoesNotExist:
            raise APIException("token 错误")
